package com.qf.sy2103.homework01.service;

import com.qf.sy2103.homework01.dao.BookDao;
import com.qf.sy2103.homework01.entity.Book;
import com.qf.sy2103.homework01.utils.FileUtils;
import com.qf.sy2103.homework01.utils.MybatisUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 *
 */
public class DataExportService {

    /**
     * 从book表中读取全部的数据并写入指定的文本文件中。
     * @throws IOException
     */
    public static void readDataAndWriteToFile() throws IOException {

        //1. 获得指定表中包含了多少条数据
        final int totalRowCount = DataExportService.getTotalRowCount();

        int pageSize = 1000; // 页大小

        int start = 0 ; // 起始的行数
        //2. 计算循环次数，并且循环获取分页数据，并且把分页数据写入指定的文本文件中
        int counts = totalRowCount/ 1000 + 1;
        for (int i = 0; i < counts; i++) {
            final List<Book> books = DataExportService.queryDataByPage(start, pageSize);
            final List<String> list = DataExportService.castBooks(books);
            FileUtils.writeListToFile(list,"output.txt");
            start += pageSize;
        }

    }

    /**
     * 查询指定页的数据
     * @param start     开始的行号
     * @param pageSiez  查询多少条数据，页大小
     * @return
     */
    public static List<Book> queryDataByPage(int start, int pageSiez){

        final BookDao bookDao = MybatisUtil.getMapper(BookDao.class);

        final List<Book> books = bookDao.querBooksByPage(start, pageSiez);

        return books;
    }

    /**
     * 获取总条数
     * @return
     */
    public static int getTotalRowCount(){

        final BookDao bookDao = MybatisUtil.getMapper(BookDao.class);

        final int totalCount = bookDao.getTotalCount();

        return totalCount;
    }

    /**
     * 把list<book>转换成 list<String>
     * @param list
     * @return
     */

    public static List<String> castBooks(List<Book> list){

        final ArrayList<String> arrayList = new ArrayList<>();

        list.forEach(book -> arrayList.add(book.toString()));

        return arrayList;
    }

}
